<?php

namespace App\Admin\Forms;

use App\Models\Withdraw;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Contracts\LazyRenderable;
use App\Services\WithdrawService;

class WithdrawVerifyFormBatch extends Form implements LazyRenderable
{
    use LazyWidget;


    // 处理请求
    public function handle(array $input)
    {
        // id转化为数组
        $id = explode(',', $input['id'] ?? null);
        $state = $input['state'] ?? 0;
        $remark = $input['remark'] ?? '';

        if (! $id) {
            return $this->response()->error('参数错误');
        }

        $withdraws = Withdraw::query()->find($id);

        if ($withdraws->isEmpty()) {
            return $this->response()->error('请选择提现申请后操作');
        }

        $withdraw_service = new WithdrawService();
        $res['state'] = true;
        $res['msg'] = "";
        // 这里改为循环批量修改
        $withdraws->each(function ($withdraw) use ($state,$remark,$withdraw_service,&$res) {
            $res2 = $withdraw_service->action($withdraw, $state, $remark);
            if($res2['state']==false){
                $res['state'] = false;
                $res['msg'] = $res2['msg'];
            }
        });
        if($res['state']==false){
            return $this->response()->error($res['msg'])->refresh();
        }
        else{
            return $this->response()->success('操作成功')->refresh();
        }
        
    }

    public function form()
    {
        $this->radio('state','状态')->required()->options([1=>'已打款',-1=>'拒绝打款'])
            ->when(-1, function (Form $form) {
                $form->text('remark','拒绝理由');
            });

        // 设置隐藏表单，传递用户id
        $this->hidden('id')->attribute('id', 'withdraw-id');
    }

    // 返回表单数据，如不需要可以删除此方法
    public function default()
    {
        return [
            'state'  => 1,
            'remark' => '',
        ];
    }
}